<template>
  <div class="detail-page">
    <a-row :gutter="20">
      <!-- 文章主体区 -->
      <a-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
        <a-card>
          <div class="bread-box">
            <!-- 面包屑导航 -->
            <a-breadcrumb>
              <a-breadcrumb-item
                ><router-link to="/home">首页</router-link></a-breadcrumb-item
              >
              <a-breadcrumb-item>技术</a-breadcrumb-item>
              <!-- 分类 -->
              <a-breadcrumb-item>{{
                blog.type ? blog.type.name : ""
              }}</a-breadcrumb-item>
              <!-- 标题 -->
              <a-breadcrumb-item>{{ blog.title }}</a-breadcrumb-item>
            </a-breadcrumb>
          </div>
          <div class="article-box">
            <div class="detailed-title">
              {{ blog.title }}
            </div>
            <div class="list-icon">
              <span
                ><a-icon type="calendar"></a-icon
                >{{ new Date(blog.createTime).toLocaleDateString() }}</span
              >
              <span
                ><a-icon type="folder"></a-icon
                >{{ blog.type ? blog.type.name : "" }}</span
              >
              <span
                ><a-icon type="user"></a-icon
                >{{ blog.user ? blog.user.nickName : "" }}</span
              >
              <span><a-icon type="fire"></a-icon>{{ blog.views }}</span>
            </div>
            <div id="detailed-content">{{ blog.content }}</div>
          </div>
        </a-card>
        <!-- 评论区 -->
        <a-card>
          <div class="comment-form-box">
            <p class="comment-title">
              真诚感谢您的留言, 您的留言会显示在文章底部
            </p>
            <!-- 表单区 -->
            <a-form-model
              ref="addCommentFormRef"
              :model="addCommentForm"
              :rules="addCommentFormRules"
              v-bind="layout"
            >
              <a-form-model-item
                has-feedback
                label=""
                prop="content"
                labelAlign="left"
              >
                <a-textarea
                  id="commentTextArea"
                  placeholder="想说点啥呢......"
                  v-model="addCommentForm.content"
                  autocomplete="off"
                  :auto-size="{ minRows: 5, maxRows: 7 }"
                />
              </a-form-model-item>
              <a-form-model-item
                has-feedback
                label="您的昵称"
                prop="nickName"
                labelAlign="left"
              >
                <a-input
                  placeholder="我怎么称呼您呢"
                  v-model="addCommentForm.nickName"
                  autocomplete="off"
                  :auto-size="{ minRows: 5, maxRows: 7 }"
                >
                  <a-icon slot="prefix" type="user" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item
                has-feedback
                label="您的邮箱"
                prop="email"
                labelAlign="left"
              >
                <a-input
                  placeholder="必填，不公开"
                  v-model="addCommentForm.email"
                  autocomplete="off"
                  :auto-size="{ minRows: 5, maxRows: 7 }"
                >
                  <a-icon slot="prefix" type="twitter-circle" theme="filled" />"
                  />
                </a-input>
              </a-form-model-item>
              <a-form-model-item :wrapper-col="{ span: 14 }">
                <a-button
                  type="primary"
                  @click="submitForm('addCommentFormRef')"
                >
                  提交
                </a-button>
                <a-button
                  style="margin-left: 10px"
                  @click="resetForm('addCommentFormRef')"
                >
                  重置
                </a-button>
              </a-form-model-item>
            </a-form-model>
          </div>
          <div class="comment-list-box">
            <h2>最新评论</h2>
            <a-list
              class="comment-list"
              :header="`共 ${commentList.length} 条评论`"
              item-layout="horizontal"
              :data-source="commentList"
            >
              <a-list-item slot="renderItem" slot-scope="item">
                <a-comment :avatar="item.avatar">
                  <a slot="author">
                    <span>{{item.nickName}} </span>
                    <a-tag v-if="item.adminComment === true" color="#87d068">博主</a-tag>
                  </a>
                  <template slot="actions">
                    <span @click="replyComments(item)">回复</span>
                  </template>
                  <p slot="content">
                    {{ item.content }}
                  </p>
                  <a-tooltip slot="datetime">
                    <span>{{ item.createTime | dateFormat }}</span>
                  </a-tooltip>
                  <!-- 回复的评论开始 -->
                  <div v-if="item.replyComments.length">
                    <a-comment v-for="i in item.replyComments" :key="i.id">
                      <template slot="actions">
                        <span @click="replyComments(i)">回复</span>
                      </template>
                      <a slot="author"
                        >{{ i.nickName
                        }} <a-tag v-if="i.adminComment === true" color="#87d068">博主</a-tag><span style="color: #1890ff; font-weight: bold"
                          >@{{ idtoNickName(i.parentCommentId) }}</span
                        ></a
                      >
                      <a-avatar slot="avatar" :src="i.avatar" />
                      <p slot="content">
                        {{ i.content }}
                      </p>
                      <a-tooltip slot="datetime">
                        <span>{{ i.createTime | dateFormat }}</span>
                      </a-tooltip>
                    </a-comment>
                  </div>
                  <!-- 回复的评论结束 -->
                </a-comment>
              </a-list-item>
            </a-list>
          </div>
        </a-card>
      </a-col>
      <!-- 目录区 -->
      <a-col :xs="0" :sm="0" :md="0" :lg="6" :xl="6">
        <a-card class="toc-card">
          <div class="toc-title">
            <a-icon type="read" />
            <span>目录</span>
          </div>
          <div id="toc" class="toc-list"></div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import Vditor from "vditor";
import "vditor/dist/index.css";

export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }

      cb(new Error("请输入合法的邮箱"));
    };
    return {
      // 请求的文章ID
      postBlogId: 0,
      // 文章内容
      blog: {},
      question: "loading...",
      //flag 判断是回复评论还是新增评论
      replyFlag: false,
      // 评论表单
      addCommentForm: {
        content: "",
        nickName: "",
        email: "",
        parentCommentId: -1,
      },
      // 评论表单的验证规则对象
      addCommentFormRules: {
        content: [
          { required: true, message: "请输入评论内容", trigger: "blur" },
        ],
        nickName: [
          { required: true, message: "昵称是必填项", trigger: "blur" },
        ],
        email: [
          { required: true, message: "邮箱是必填项", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
      },
      layout: {
        labelCol: { span: 0 },
        wrapperCol: { span: 24 },
      },
      //评论列表
      commentList: [],
    };
  },
  computed: {
    //从id到nickName
    idtoNickName() {
      return function (id) {
        let tmp = ''
        this.commentList.forEach(item => {
          if(item.id === id){
            tmp = item.nickName
          }else{
            item.replyComments.forEach(i => {
              if(i.id === id){
                tmp = i.nickName
              }
            })
          }
        })
        return tmp
      };
    },
  },
  mounted() {
    this.postBlogId = this.$route.params.blogId;
    // console.log(this.postBlogId)
    this.getDetailBlog();
    //获取评论列表
    this.getCommentList();
  },
  methods: {
    async getDetailBlog() {
      try {
        const { data: res } = await this.$http.get("blog/" + this.postBlogId);
        // console.log(res);
        this.blog = res.data;
        this.question = "请求完成";
      } catch (e) {
        console.log(e);
      }
    },
    renderMarkdown(md) {
      Vditor.preview(document.getElementById("detailed-content"), md, {
        mode: "light",
        anchor: 1,
        after: function () {
          Vditor.outlineRender(
            document.getElementById("detailed-content"),
            document.getElementById("toc")
          );
          // 添加类名
          let span_list = document.querySelectorAll("[data-target-id]");
          for (let i = 0; i < span_list.length; i++) {
            span_list[i].classList.add("display-block");
            span_list[i].onclick = function () {
              for (let j = 0; j < span_list.length; j++) {
                span_list[j].classList.remove("current");
              }
              span_list[i].classList.add("current");
            };
          }
          // 增加鼠标滑动效果
          const headingElements = [];
          Array.from(
            document.getElementById("detailed-content").children
          ).forEach((item) => {
            if (
              item.tagName.length === 2 &&
              item.tagName !== "HR" &&
              item.tagName.indexOf("H") === 0
            ) {
              headingElements.push(item);
            }
          });
          let toc = [];
          window.addEventListener("scroll", () => {
            const scrollTop = window.scrollY;
            toc = [];
            headingElements.forEach((item) => {
              toc.push({
                id: item.id,
                offsetTop: item.offsetTop,
              });
            });

            const currentElement = document.querySelector(".current");
            for (let i = 0, iMax = toc.length; i < iMax; i++) {
              if (scrollTop < toc[i].offsetTop - 30) {
                if (currentElement) {
                  currentElement.classList.remove("current");
                }
                let index = i > 0 ? i - 1 : 0;
                document
                  .querySelector('span[data-target-id="' + toc[index].id + '"]')
                  .classList.add("current");
                break;
              }
            }
          });
        },
      });
      // 修改css样式
      document.getElementById("toc").classList.add("toc-style");
    },
    //获取评论数据
    async getCommentList() {
      try {
        const { data: res } = await this.$http.get(
          "comment/blog/" + this.postBlogId
        );
        this.commentList = res.data;
      } catch (e) {
        console.log(e);
      }
    },
    // 提交评论表单
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //console.log(this.addCommentForm);
          this.addCommentForm["blogId"] = this.postBlogId;
          if (!this.replyFlag) {
            this.addCommentForm["parentCommentId"] = -1;
          }
          //发送请求
          try {
            const { data: res } = await this.$http.post(
              "comment",
              this.addCommentForm
            );
            //console.log(res)
            this.commentList = res.data;
            if (!this.replyFlag) {
              this.$message.success("发表评论成功！");
            } else if (this.replyFlag) {
              this.$message.success("回复评论成功！");
              //重置placeholder
              document.getElementById("commentTextArea").placeholder =
                "想说点啥呢......";
            }
            //重置flag
            this.replyFlag = false;
            //滚动页面
            let targetElement = document.getElementsByClassName(
              "comment-list-box"
            )[0];
            targetElement.scrollIntoView({
              behavior: "smooth",
              block: "center",
              inline: "nearest",
            });
            //重置表单
            this.resetForm("addCommentFormRef");
          } catch (e) {
            this.$message.error("评论失败！");
            console.log(e);
          }
        } else {
          this.$message.error("表单检验不通过！");
          return false;
        }
      });
    },
    // 重置评论表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 回复评论
    replyComments(item) {
      console.log(item);
      //滚动屏幕
      let targetElement = document.getElementsByClassName(
        "comment-form-box"
      )[0];
      targetElement.scrollIntoView({
        behavior: "smooth",
        block: "center",
        inline: "nearest",
      });
      let { id: commentId, nickName } = { ...item };
      //设置输入域
      document.getElementById("commentTextArea").placeholder = "@" + nickName;
      //获得焦点
      document.getElementById("commentTextArea").focus();
      this.replyFlag = true;
      this.addCommentForm.parentCommentId = commentId;
    },
    //根据id查询评论
    async getCommentInfoById(id) {
      const { data: res } = await this.$http.get("comment/" + id);
      return res.nickName;
    },
  },
  watch: {
    question(question) {
      this.renderMarkdown(this.blog.content);
    },
  },
};
</script>

<style lang="less" scoped>
.detail-page {
  padding: 63px 15px 0 15px;
  max-width: 1200px;
  margin: 0 auto;
}
.bread-box {
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}
.detailed-title {
  font-weight: bolder;
  font-size: 23px;
  text-align: center;
  padding: 16px;
}
.list-icon {
  font-weight: bold;
  text-align: center;
  color: #828282;
  padding: 8px 0;
  margin-bottom: 30px;
  span {
    padding: 0 10px;
    i {
      color: #1890ff;
      margin-right: 5px;
    }
  }
}
.ant-row {
  .ant-col:nth-child(2) {
    position: sticky;
    top: 63px;
    .ant-card {
      .ant-card-body {
        padding: 10px !important;
      }
    }
    // 目录区
    .toc-title {
      font-size: 18px;
      color: #1890ff;
      margin-bottom: 10px;
      i {
        margin-right: 10px;
      }
    }
    .toc-list {
      max-height: 500px;
      overflow-y: auto;
    }
  }
}
// 评论头部信息
.comment-title {
  font-size: 15px;
  font-weight: bolder;
  margin-bottom: 15px;
}
</style>
<style lang="less">
// 目录样式
.toc-style {
  ul {
    list-style: none !important;
    padding: 0;
    margin-left: 5px;
    span {
      // display: block;
      cursor: pointer;
      &:hover {
        color: #1890ff;
      }
    }
    .current {
      border-left: 1px solid #4285f4;
      color: #4285f4;
      background-color: #f6f8fa;
    }
  }
}
.display-block {
  display: block;
}
.toc-card {
  .ant-card-body {
    padding: 15px 0px 24px 15px !important;
  }
}
</style>